package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;

import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.utils.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.apache.ibatis.io.Resources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

/**
 * @program: cs-mall_32th
 * @description:
 * @author: YuHui
 * @create: 2021-08-24 21:32
 **/
@Service
@Slf4j
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender javaMailSender;

    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {

        UserRegisterResponse response = new UserRegisterResponse();

        try{
            //判空
            registerRequest.requestCheck();

            //判重
            volidUserNameRepeat(registerRequest);

            Member member = new Member();
            member.setUsername(registerRequest.getUserName());
            member.setEmail(registerRequest.getEmail());

            //aes
            String password = new AESUtil(registerRequest.getUserPwd()).encrypt();
            member.setPassword(password);

            Date date = new Date();
            member.setCreated(date);
            member.setUpdated(date);
            member.setIsVerified("N");
            member.setState(1);

            int effectRows = memberMapper.insertSelective(member);
            if (effectRows != 1) {
                response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return response;
            }

            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(member.getUsername());

            String uuid = UUID.randomUUID().toString();
            String replace = uuid.replace("-", "");
            userVerify.setUuid(replace);
            userVerify.setRegisterDate(date);
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("N");

            int rows = userVerifyMapper.insertSelective(userVerify);
            if (rows != 1) {
                response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
                return response;
            }

            //发送用户激活邮件，激活邮件应该是一个链接，有一个接口去处理我们的用户激活
//            Runnable runnable = () -> {
//                sendEmail(replace, registerRequest);
//            };
//            Thread thread = new Thread(runnable);
//            thread.start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendEmail(replace, registerRequest);
                }
            }).start();

            //用户注册成功
            log.info("注册成功，注册参数为request:{}", JSON.toJSONString(registerRequest));

            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
            //参数或数据库
            log.error(" "+e);
            response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());

        }

        return response;
    }

    /**
     * 发送验证邮箱
     * @param uuid
     * @param registerRequest
     */
    private void sendEmail(String uuid, UserRegisterRequest registerRequest){
        Properties properties = new Properties();
        try {
            properties.load(Resources.getResourceAsStream("mail-config.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(properties.getProperty("mail.subject"));
        message.setFrom(properties.getProperty("mail.from"));
        message.setTo(registerRequest.getEmail());

//        StringBuilder stringBuilder = new StringBuilder();
//        stringBuilder.append("\n").append("激活链接：").append("http://localhost:9999/user/verify?uid=").append(uuid).append("&username=").append(registerRequest.getUserName()).append("\n");
//        message.setText(stringBuilder.toString());
//        System.out.println(stringBuilder.toString());

        String text = "\n激活链接：http://localhost:9999/user/verify?uid=" + uuid + "&username=" + registerRequest.getUserName() + "\n";
        message.setText(text);
        System.out.println(text);

        javaMailSender.send(message);

    }


    /**
     * 验证用户名是否重复
     * @param registerRequest
     */
    private void volidUserNameRepeat(UserRegisterRequest registerRequest) {

        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", registerRequest.getUserName());
        List<Member> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(), SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage()
            );
        }
    }

}
